﻿
/********************************************************
 // Module Name    : Desktop ShortCuts
 // Purpose        : Show Desktop Shortcut Items on main screen
 // Class Used     : IHost,Envs.cs,
 // Created By     : Harwinder 
 // Date           : --
**********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightDesktop.Controls;
using VAdvantage.Utility;
using System.Reflection;
using VAdvantage.Apps;
using VAdvantage.Logging;
using System.Data;
using VAdvantage.Model;
using System.Text;

namespace VAdvantage.MainScreen
{
    public partial class DesktopShortcutContainer : UserControl, IHost
    {
        #region Declaration
        /* contain Image Source for Shortcut */
        List<ImageSource> lstImgSource = new List<ImageSource>();
        #endregion

        /// <summary>
        /// std Constructor
        /// </summary>
        public DesktopShortcutContainer()
        {
            InitializeComponent();
        }

        #region Functions

        /// <summary>
        /// Initilize 'Create Shortcut' process 
        /// </summary>
        public void Load()
        {
            bool isBaseLang = Envs.IsBaseLanguage(Envs.GetCtx(), "AD_Shortcut");


            int AD_Client_ID = Envs.GetCtx().GetAD_Client_ID();
            StringBuilder sql = new StringBuilder(@" SELECT o.Name AS Name, 
                                    o.AD_Image_ID AS AD_Image_ID,
                                  o.Classname AS ClassName  ,
                                   o.AD_ShortCut_ID,
                                  o.Action  AS Action   ,
                                  (
                                  CASE
                                    WHEN o.action = 'W'
                                    THEN o.ad_window_id
                                    WHEN o.action='P'
                                    OR o.action  ='R'
                                    THEN o.ad_process_id
                                    WHEN o.action = 'B'
                                    THEN o.ad_workbench_id
                                    WHEN o.action = 'T'
                                    THEN o.ad_task_id
                                    WHEN o.action = 'X'
                                    THEN o.ad_form_id
                                    WHEN o.action ='F'
                                    THEN o.ad_workflow_id
                                    ELSE 0
                                  END ) AS ActionID,
                                
                                  (
                                  CASE
                                    WHEN
                                     (SELECT COUNT(*)
                                       FROM Ad_Shortcut i
                                      WHERE i.parent_id = o.ad_shortcut_id and Ischild = 'Y') >0
                                    THEN 'Y'
                                    ELSE 'N'
                                  END) AS HasChild, o.ad_shortcut_id as ID,  o.Url as Url,
                                  
                                  (select count(*) from AD_ShortcutParameter where AD_ShortCut_ID=o.AD_ShortCut_ID) as hasPara,");

            if(isBaseLang)
            {
                sql.Append(" COALESCE(o.DisplayName,o.Name) as Name2");
            }
            else
            {
                sql.Append(" COALESCE(trl.Name,o.Name) as Name2") ;
            }
            sql.Append(" FROM AD_Shortcut o ");
            if(!isBaseLang)
            {
                sql.Append(" INNER JOIN AD_Shortcut_Trl trl ON o.AD_Shortcut_ID = trl.AD_Shortcut_ID AND trl.AD_Language =")
                .Append("'").Append(Envs.GetAD_Language(Envs.GetCtx())).Append("'");
            }

            sql.Append(" WHERE o.AD_Client_ID = 0 AND o.IsActive ='Y' AND o.IsChild = 'N' ");

            sql.Append(@"ANd (o.AD_Window_ID IS NULL OR EXISTS (SELECT * FROM ad_window_access w WHERE w.AD_Window_ID=o.AD_Window_ID AND w.isreadwrite='Y' and ad_role_id=" + Envs.GetCtx().GetAD_Role_ID() + @"))
                        ANd (o.AD_Form_ID IS NULL OR EXISTS (SELECT * FROM ad_Form_access f WHERE f.ad_form_id=o.AD_Form_ID AND f.isreadwrite='Y' and ad_role_id=" + Envs.GetCtx().GetAD_Role_ID() + @"))
                        ANd (o.AD_Process_ID IS NULL OR EXISTS (SELECT * FROM ad_process_access p WHERE p.ad_process_id=o.AD_Process_ID AND p.isreadwrite='Y' and ad_role_id=" + Envs.GetCtx().GetAD_Role_ID() + @"))");
                        
            
           sql.Append("  ORDER BY SeqNo");

            System.Data.DataSet ds = null;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                try
                {
                    ds = DataBase.DB.ExecuteDataset(sql.ToString(), null);
                }
                catch
                {
                    return;
                }
                Dictionary<int, DataSet> dsParams = new Dictionary<int, DataSet>();

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {

                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        int AD_Image_ID = Utility.Util.GetValueOfInt(dr["AD_Image_ID"]);
                        if (AD_Image_ID > 0)
                        {
                            lstImgSource.Add(new Model.MImage(Envs.GetCtx(), AD_Image_ID, null).GetImage());
                        }
                        else
                        {
                            lstImgSource.Add(null);
                        }

                        if (Util.GetValueOfInt(dr["HASPARA"]) > 0)
                        {
                            string strSql = "SELECT parametername, parametervalue,ISENCRYPTED FROM AD_ShortCutParameter WHERE AD_ShortCut_ID=" + Util.GetValueOfInt(dr["AD_SHORTCUT_ID"]);
                            DataSet dsPara = DataBase.DB.ExecuteDataset(strSql, null);
                            dsParams[Util.GetValueOfInt(dr["AD_SHORTCUT_ID"])] = dsPara;
                        }
                    }
                }

                Dispatcher.BeginInvoke(() => CreateShortCuts(ds, dsParams));
            });
        }

        /// <summary>
        /// Create shortcut
        /// </summary>
        /// <param name="ds"></param>
        private void CreateShortCuts(System.Data.DataSet ds, Dictionary<int, DataSet> dsParam)
        {
            if (ds == null || ds.Tables[0].Rows.Count < 1)
                return;
            int i = 0;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                DesktopShortcutItem itm = new DesktopShortcutItem();
                itm.Icon = lstImgSource[i];
                itm.ShortcutName = Util.GetValueOfString(dr["Name2"]);
                itm.Action = Util.GetValueOfString(dr["Action"]);
                itm.ActionID = Util.GetValueOfInt(dr["ActionID"]);
                itm.SpecialAction = Util.GetValueOfString(dr["ClassName"]);
                itm.ActionName = Util.GetValueOfString(dr["Name"]);
                itm.HasChild = "Y".Equals(Util.GetValueOfString(dr["HasChild"]));
                StringBuilder builder = new StringBuilder();

                if (Util.GetValueOfInt(dr["HASPARA"]) > 0)
                {
                    DataSet dsParams = dsParam[Util.GetValueOfInt(dr["AD_SHORTCUT_ID"])];
                    if (dsParams != null && dsParams.Tables[0].Rows.Count > 0)
                    {
                        for (int np = 0; np < dsParams.Tables[0].Rows.Count; np++)
                        {
                            if (dsParams.Tables[0].Rows[np]["PARAMETERVALUE"] != null && dsParams.Tables[0].Rows[np]["PARAMETERVALUE"].ToString() != "")
                            {
                                string variableName = dsParams.Tables[0].Rows[np]["PARAMETERVALUE"].ToString();
                                String columnName = string.Empty;
                                string env = string.Empty;
                                if (variableName.Contains("@"))
                                {
                                    int index = variableName.IndexOf("@");
                                    columnName = variableName.Substring(index + 1);
                                    index = columnName.IndexOf("@");
                                    if (index == -1)
                                    {
                                        break;
                                    }
                                    columnName = columnName.Substring(0, index);
                                    env = Envs.GetCtx().GetContext(columnName);
                                    // MessageBox.Show(columnName + " " + env);
                                }
                                else
                                {
                                    if (dsParams.Tables[0].Rows[np]["PARAMETERNAME"] != null && dsParams.Tables[0].Rows[np]["PARAMETERVALUE"].ToString() != "")
                                    {
                                        columnName = dsParams.Tables[0].Rows[np]["PARAMETERNAME"].ToString();
                                    }
                                    env = variableName;
                                }

                                if (env.Length == 0)
                                {
                                    break;
                                }

                                if (dsParams.Tables[0].Rows[np]["ISENCRYPTED"].ToString().Equals("Y", StringComparison.OrdinalIgnoreCase))
                                {
                                    env = SecureEngine.Encrypt(env);
                                }
                                if (columnName.StartsWith("#"))
                                {
                                    while (columnName.StartsWith("#"))
                                    {
                                        columnName = columnName.Substring(1);
                                    }
                                }

                                builder.Append(columnName).Append("=").Append(env).Append('&');
                            }
                        }
                        builder.ToString().TrimEnd('&');
                    }
                }

                if ((builder.ToString().Length > 0))
                {
                    itm.Url = Util.GetValueOfString(dr["Url"]) + builder.ToString();
                }
                else
                {
                    itm.Url = Util.GetValueOfString(dr["Url"]);
                }

                itm.KeyID = Util.GetValueOfInt(dr["ID"]);
                itm.Explorer = Envs.Desktop;
                itm.Margin = new Thickness(3, 5, 1, 4);
                itm.DoubleClick += new RoutedEventHandler(Item_DoubleClick);
                wpContainer.Children.Add(itm);
                i++;
            }
            lstImgSource.Clear();
            lstImgSource = null;
        }

        /// <summary>
        /// Add Desktop ShortCut
        /// </summary>
        /// <param name="name">name of shortcut</param>
        /// <param name="action">entity Action</param>
        /// <param name="specialAction">name of class</param>
        /// <param name="actionID">id of action</param>
        /// <param name="icon">image source for shortcut icon</param>
        private void AddShortCut(String name, string action, String specialAction, int actionID, ImageSource icon)
        {
            DesktopShortcutItem itm = new DesktopShortcutItem();
            itm.Icon = icon;
            itm.ShortcutName = name;
            itm.Action = action;
            itm.ActionID = actionID;
            itm.SpecialAction = specialAction;
            itm.Explorer = Envs.Desktop;
            itm.Margin = new Thickness(3, 5, 1, 4);
            itm.DoubleClick += new RoutedEventHandler(Item_DoubleClick);
            wpContainer.Children.Add(itm);
        }

        /// <summary>
        /// Show Entity Against Action
        /// </summary>
        /// <param name="action"></param>
        /// <param name="cmd"></param>
        internal void StartAction(string action, int cmd)
        {
            AMenuStartItem aStart = new AMenuStartItem(cmd, true, "", this);
            action = action.Trim();
            if (action.Equals("W"))				//	Window
            {
                aStart.StartWindow(0, cmd);
            }
            else if (action.Equals("P") || action.Equals("R"))	//	Process & Report
            {
                aStart.StartProcess(cmd);
            }
            else if (action.Equals("B"))		//	Workbench
            {
                aStart.StartWindow(cmd, 0);
            }
            else if (action.Equals("F"))		//	WorkFlow
            {
                //if (_isMenu)
                //    cmd = Utility.Util.GetValueOfInt(dr["AD_Workflow_ID"]);
                //else
                //    cmd = Utility.Util.GetValueOfInt(dr["Workflow_ID"]);
            }
            else if (action.Equals("T"))		//	Task
            {
                aStart.StartTask(cmd);
            }
            else if (action.Equals("X"))		//	Form
            {
                aStart.StartForm(cmd);
            }
            else
            {
                VLogger.Get().Log(Level.SEVERE, "No valid Action in ID=" + cmd);
            }
            aStart = null;
        }

        #endregion

        #region "Events"
        /// <summary>
        /// Double ClickEvent handler of Shortcut
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Item_DoubleClick(object sender, RoutedEventArgs e)
        {
            Envs.SetBusyIndicator(true);
            DesktopShortcutItem dsi = sender as DesktopShortcutItem;

            //1   Contain Child ShortCut

            if (dsi.HasChild)
            {
                SettingDialog sd = new SettingDialog(dsi.KeyID);
                sd.Show();
            }

            //2 If URL

            else if (!string.IsNullOrEmpty(dsi.Url))
            {
                Envs.StartBrowser(dsi.Url);
                Envs.SetBusyIndicator(false);
            }

            // 3 Special Class
            else if (!string.IsNullOrEmpty(dsi.SpecialAction))
            {
                //check name has moduleprefix
                string className = dsi.SpecialAction;
                //
                //Get form Name
                String formName = dsi.ActionName; // className.Substring(className.LastIndexOf('.') + 1);

                try
                {
                    Assembly asm = null;
                    Type type = null;

                    /************  Module ****************/
                    try
                    {
                        //string formName = className.Substring(className.LastIndexOf('.') + 1);
                        Tuple<String, String> asmInfo = null;
                        if (Envs.HasModulePrefix(formName, out asmInfo))
                        {
                            asm = Assembly.Load(asmInfo.Item1);
                            type = asm.GetType(className);
                        }
                    }
                    catch (Exception ex)
                    {
                        VLogger.Get().Warning("Assembly => " + ex.Message);
                    }
                    /********************* END ******************/

                    if (type == null)
                    {
                        try
                        {
                            asm = Assembly.Load(VAdvantage.DataBase.GlobalVariable.PRODUCT_NAME);
                            type = asm.GetType(className);
                        }
                        catch
                        {
                            //asm = Assembly.Load(GlobalVariable.ASSEMBLY_NAME);
                        }
                    }

                    /*End Customization */

                    if (type == null)
                    {
                        type = Type.GetType(className);
                    }

                    if (type != null && type.IsClass)
                    {
                        try
                        {
                            object instance = Activator.CreateInstance(type);
                            if (instance is Form)
                            {
                                Form frm = (Form)instance;
                                Utility.Envs.RegisterWindowForm(frm);
                                frm.Show();
                            }
                            else if (instance is ChildWindow)
                            {
                                ((ChildWindow)instance).Show();
                            }
                        }
                        catch (Exception ex)
                        {



                            VAdvantage.Logging.VLogger.Get().Warning("No Instance for " + type.FullName + " (" + ex.ToString() + ")");
                        }
                    }
                    else
                    {
                        VLogger.Get().Info("Type not found against " + className);
                    }
                }
                catch (Exception exx)
                {
                    Envs.SetBusyIndicator(false);
                    VLogger.Get().Severe("Error " + className);
                    // return false;
                }
                Envs.SetBusyIndicator(false);
            }


            else //Entity Action
            {
                if (String.IsNullOrEmpty(dsi.Action) || dsi.ActionID < 1)
                {
                    VLogger.Get().Info("No action or action_ID against shortcut");
                    Envs.SetBusyIndicator(false);
                    return;
                }
                StartAction(dsi.Action, dsi.ActionID);
            }
       //     Envs.SetBusyIndicator(false);
            
        }

        /// <summary>
        /// Check If workSpace is allowed or Not
        /// </summary>

        #endregion

        #region IHOST

        public void OnLoginCompleted()
        {
            //throw new NotImplementedException();
        }

        public void OnMenuLoad()
        {
            //throw new NotImplementedException();
        }

        public Explorer GetExplorer
        {
            get { return Envs.Desktop; }
        }

        public bool ShowBusyIndicator
        {
            get
            {
                return false;
                //throw new NotImplementedException();
            }
            set
            {
                // throw new NotImplementedException();
            }
        }

        public void StartMenuItemID(int id)
        {
            //throw new NotImplementedException();
        }
        #endregion
    }
}
